<?php
	include ("config.php"); /*Traemos el archivo config*/
	// Crea el formulario
	$action = isset ($_POST["action"]) ? $_POST["action"] : ""; //Comprueba si hay una accion
	if (empty ($action)) { //si no hay accion
		// Crea el formulario
		$output = "<div style='display:none'>
			<div class='contact-top'></div>
			<div class='contact-content'>
				<h1 class='contact-title'>Registrate</h1>
				<div class='contact-loading' style='display:none'></div>
				<div class='contact-message' style='display:none'></div>
				<form action='#' style='display:none'>
					<label for='contact-name'>*Nombre:</label>			
					<input type='text' id='contact-name' class='contact-input' name='firstname' tabindex='1001' maxlength=16/>
					<br><div class ='name-error' style='display:none'></div>
					<label for='contact-lastname'>*Apellido:</label>
					<input type='text' id='contact-lastname' class='contact-input' name='lastname' tabindex='1002' maxlength=35 />
					<br><div class='lastname-error' style='display:none'></div>
					<div id='user-form'>
					<label for='contact-login'>*Usuario:</label>
					<input type='text' id='contact-login' class='contact-input' name='username' tabindex='1003' maxlength=16'/>
					<div id='msgUsuario'></div>
				    <br><div class='user-error' style='display:none'></div>
				    </div>
				   	<div id= 'password-form'>
					<label for='contact-pass1'>*Contraseña:</label>
					<input type='password' id='contact-pass1' class='contact-input' name='pass1' tabindex='1004' maxlength=16/>
					</div>
					<br>
					<div class='pass-error' style='display:none'></div>
					<label for='contact-pass2'>*Confirma tu contraseña:</label>
					<input type='password' id='contact-pass2' class='contact-input' name='pass2' tabindex='1005'  maxlength=16/>
					<label for='contact-email'>*Email:</label>
					<input type='text' id='contact-email' class='contact-input' name='email' tabindex='1006' maxlength=35/>
					<br><div class='mail-error' style='display:none'></div>
					<label for='contact-date'>Fecha de Nacimiento:</label>
					<select id='contact-day' name='day' tabindex='1007'>
				      	<option value='0'>Día</option>
						<option value='01'>01</option>
						<option value='02'>02</option>
						<option value='03'>03</option>
						<option value='04'>04</option>
						<option value='05'>05</option>
						<option value='06'>06</option>
						<option value='07'>07</option>
						<option value='08'>08</option>
						<option value='09'>09</option>
						<option value='10'>10</option>
						<option value='11'>11</option>
						<option value='12'>12</option>
						<option value='13'>13</option>
						<option value='14'>14</option>
						<option value='15'>15</option>
						<option value='16'>16</option>
						<option value='17'>17</option>
						<option value='18'>18</option>
						<option value='19'>19</option>
						<option value='20'>20</option>
						<option value='21'>21</option>
						<option value='22'>22</option>
						<option value='23'>23</option>
						<option value='24'>24</option>
						<option value='25'>25</option>
						<option value='26'>26</option>
						<option value='27'>27</option>
						<option value='28'>28</option>
						<option value='29'>29</option>
						<option value='30'>30</option>
						<option value='31'>31</option>
					</SELECT>
					<select id='contact-month' name='month' tabindex='1008'>
						<option value='00'>Mes</option>	
				      	<option value='01'>Enero</option>
						<option value='02'>Febrero</option>
						<option value='03'>Marzo</option>
						<option value='04'>Abril</option>
						<option value='05'>Mayo</option>
						<option value='06'>Junio</option>
						<option value='07'>Julio</option>
						<option value='08'>Agosto</option>
						<option value='09'>Septiembre</option>
						<option value='10'>Octubre</option>
						<option value='11'>Noviembre</option>
						<option value='12'>Diciembre</option> 
					</SELECT>
					<select id='contact-year' name='year' tabindex='1009'>
						<option value='0'>Año</option>
						<option value='95'>1995</option>
						<option value='94'>1994</option>
						<option value='93'>1993</option>
						<option value='92'>1992</option>
						<option value='91'>1991</option>
						<option value='90'>1990</option>
						<option value='89'>1989</option>
						<option value='88'>1988</option>
						<option value='87'>1987</option>
						<option value='86'>1986</option>
						<option value='85'>1985</option>
						<option value='84'>1984</option>
						<option value='83'>1983</option>
						<option value='82'>1982</option>
						<option value='81'>1981</option>
						<option value='80'>1980</option>
						<option value='79'>1979</option>
						<option value='78'>1978</option>
						<option value='77'>1977</option>
						<option value='76'>1976</option>
						<option value='75'>1975</option>
						<option value='74'>1974</option>
						<option value='73'>1973</option>
						<option value='72'>1972</option>
						<option value='71'>1971</option>
						<option value='70'>1970</option>
						<option value='69'>1969</option>
						<option value='68'>1968</option>
						<option value='67'>1967</option>
						<option value='66'>1966</option>
						<option value='65'>1965</option>
						<option value='64'>1964</option>
						<option value='63'>1963</option>
						<option value='62'>1962</option>
						<option value='61'>1961</option>
						<option value='60'>1960</option>
						<option value='59'>1959</option>
						<option value='58'>1958</option>
						<option value='57'>1957</option>
						<option value='56'>1956</option>
						<option value='55'>1955</option>
						<option value='54'>1954</option>
						<option value='53'>1953</option>
						<option value='52'>1952</option>
						<option value='51'>1951</option>
						<option value='50'>1950</option>
						<option value='49'>1949</option>
						<option value='48'>1948</option>
						<option value='47'>1947</option>
						<option value='46'>1946</option>
						<option value='45'>1945</option>
						<option value='44'>1944</option>
						<option value='43'>1943</option>
						<option value='42'>1942</option>
						<option value='41'>1941</option>
						<option value='40'>1940</option>
						<option value='39'>1939</option>
						<option value='38'>1938</option>
						<option value='37'>1937</option>
						<option value='36'>1936</option>
						<option value='35'>1935</option>
						<option value='34'>1934</option>
						<option value='33'>1933</option>
						<option value='32'>1932</option>
						<option value='31'>1931</option>
						<option value='30'>1930</option>
						<option value='29'>1929</option>
						<option value='28'>1928</option>
						<option value='27'>1927</option>
						<option value='26'>1926</option>
						<option value='25'>1925</option>
						<option value='24'>1924</option>
						<option value='23'>1923</option>
						<option value='22'>1922</option>
						<option value='21'>1921</option>
						<option value='20'>1920</option>
						<option value='19'>1919</option>
						<option value='18'>1918</option>
						<option value='17'>1917</option>
						<option value='16'>1916</option>
						<option value='15'>1915</option>
						<option value='14'>1914</option>
						<option value='13'>1913</option>
						<option value='12'>1912</option>
						<option value='11'>1911</option>
					</SELECT>
					<br>
					<button type='submit' class='contact-send contact-button' tabindex='1010'>Enviar</button>
					<button type='submit' class='contact-cancel contact-button simplemodal-close' tabindex='1011'>Cancelar</button>
					<label>&nbsp;</label>
				</form>
			</div>
		</div>";

		echo $output;
	} else
		if ($action == "send") {

			/*Recibimos las variables por el metodo POST*/

			$username = htmlspecialchars(trim($_POST['username']));

			$pass1 = $_POST['pass1'];

			$pass2 = $_POST['pass2'];

			$firstname = htmlspecialchars($_POST['firstname']);

			$lastname = htmlspecialchars($_POST['lastname']);

			$email = htmlspecialchars($_POST['email']);

			$date = htmlspecialchars($_POST['year']) . '-' . htmlspecialchars($_POST['month']) . '-' . htmlspecialchars($_POST['day']);

			/*----------Hacemos la consulta-----------*/
			$link = mysql_connect($server, $dbuser, $dbpass) or die("<center>No se puede conectar con la base de datos\n</center>\n");

			$query = sprintf("SELECT Usuario FROM Datos_Usuarios WHERE Datos_Usuarios.Usuario='%s'", mysql_real_escape_string($username));

			$result = mysql_db_query($database, $query, $link);

			if (mysql_num_rows($result)) {

				echo "Se ha producido un error, intentalo más tarde";

				/*--insertar fallo en la bd¿¿¿--*/

			} else {

				mysql_free_result($result);

				/* Ahora comprobamos que los dos pass coinciden */

				if ($pass1 != $pass2) {

					echo "Se ha producido un error, intentalo más tarde";

				} else {

					$fecha = time();
					
					$fecha_con_formato = date("Y-m-d H:i:s",$fecha);

					$pass1 = md5($pass1);

					$query = sprintf("INSERT INTO Datos_Usuarios (Nombre, Apellidos, Password, Correo, usuario, FechaNacimiento, FechaInsercion) VALUES ('%s','%s', '%s','%s','%s','%s','%s')", mysql_real_escape_string($firstname), mysql_real_escape_string($lastname), ($pass1), mysql_real_escape_string($email), mysql_real_escape_string($username), mysql_real_escape_string($date), mysql_real_escape_string($fecha_con_formato));

					$result = mysql_db_query($database, $query, $link);

					if (mysql_affected_rows()) {

						echo "Usuario registrado";

					} else {

						echo "Se ha producido un error, intentalo más tarde";

					} /* Cierre del else */

				} /* Cierre del else que corresponde a if(mysql_affected_rows.....) */

			} /* Cierre del else que corresponde a if(mysql_num_rows...) */
		}

	function smcf_token($s) {
		return md5("smcf-" . $s . date("WY"));
	}

	// Validate and send email
	function smcf_send($name, $email, $subject, $message, $cc) {
		global $to, $extra;

		// Filter and validate fields
		$name = smcf_filter($name);
		$subject = smcf_filter($subject);
		$email = smcf_filter($email);
		if (!smcf_validate_email($email)) {
			$subject .= " - invalid email";
			$message .= "\n\nBad email: $email";
			$email = $to;
			$cc = 0; // do not CC "sender"
		}

		// Add additional info to the message
		if ($extra["ip"]) {
			$message .= "\n\nIP: " . $_SERVER["REMOTE_ADDR"];
		}
		if ($extra["user_agent"]) {
			$message .= "\n\nUSER AGENT: " . $_SERVER["HTTP_USER_AGENT"];
		}

		// Set and wordwrap message body
		$body = "From: $name\n\n";
		$body .= "Message: $message";
		$body = wordwrap($body, 70);

		// Build header
		$headers = "From: $email\n";
		if ($cc == 1) {
			$headers .= "Cc: $email\n";
		}
		$headers .= "X-Mailer: PHP/SimpleModalContactForm";

		// UTF-8
		if (function_exists('mb_encode_mimeheader')) {
			$subject = mb_encode_mimeheader($subject, "UTF-8", "B", "\n");
		} else {
			// you need to enable mb_encode_mimeheader or risk 
			// getting emails that are not UTF-8 encoded
		}
		$headers .= "MIME-Version: 1.0\n";
		$headers .= "Content-type: text/plain; charset=utf-8\n";
		$headers .= "Content-Transfer-Encoding: quoted-printable\n";

		// Send email
		@ mail($to, $subject, $body, $headers) or die("Unfortunately, a server issue prevented delivery of your message.");
	}

	// Remove any un-safe values to prevent email injection
	function smcf_filter($value) {
		$pattern = array (
			"/\n/",
			"/\r/",
			"/content-type:/i",
			"/to:/i",
			"/from:/i",
			"/cc:/i"
		);
		$value = preg_replace($pattern, "", $value);
		return $value;
	}

	// Validate email address format in case client-side validation "fails"
	function smcf_validate_email($email) {
		$at = strrpos($email, "@");

		// Make sure the at (@) sybmol exists and  
		// it is not the first or last character
		if ($at && ($at < 1 || ($at +1) == strlen($email)))
			return false;

		// Make sure there aren't multiple periods together
		if (preg_match("/(\.{2,})/", $email))
			return false;

		// Break up the local and domain portions
		$local = substr($email, 0, $at);
		$domain = substr($email, $at +1);

		// Check lengths
		$locLen = strlen($local);
		$domLen = strlen($domain);
		if ($locLen < 1 || $locLen > 64 || $domLen < 4 || $domLen > 255)
			return false;

		// Make sure local and domain don't start with or end with a period
		if (preg_match("/(^\.|\.$)/", $local) || preg_match("/(^\.|\.$)/", $domain))
			return false;

		// Check for quoted-string addresses
		// Since almost anything is allowed in a quoted-string address,
		// we're just going to let them go through
		if (!preg_match('/^"(.+)"$/', $local)) {
			// It's a dot-string address...check for valid characters
			if (!preg_match('/^[-a-zA-Z0-9!#$%*\/?|^{}`~&\'+=_\.]*$/', $local))
				return false;
		}

		// Make sure domain contains only valid characters and at least one period
		if (!preg_match("/^[-a-zA-Z0-9\.]*$/", $domain) || !strpos($domain, "."))
			return false;

		return true;
	}

	exit;

?>
